﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using ElectrosLtd.Models;
using Common;
using System.Diagnostics;

namespace ElectrosLtd.Controllers
{
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LoginModel lm)
        {
            if (ModelState.IsValid)
            {
                if (new UsersServ.WCFUsersClient().IsAuthenticationValid(lm.Username, lm.Password))
                {
                    //display the username in the header
                    FormsAuthentication.RedirectFromLoginPage(lm.Username, true);
                                        
                    return RedirectToAction("Index", "Home");

                    //Role usersR = new UsersServ.WCFUsersClient().GetUserRoles(lm.Username);
                    //new UsersServ.WCFUsersClient().GetMainMenus();
                }                
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View();
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        public ActionResult Registration()
        {
            System.Diagnostics.Process.Start("C:\\Users\\Anthony\\Documents\\visual studio 2010\\Projects\\ElectrosLtd\\TokenApplication\\bin\\Debug\\TokenApplication.exe");
            
            new UsersServ.WCFUsersClient().GetCountries();
            return View(new RegistrationModel());
        }

        //method to display that registration was successful
        public ActionResult RegistrationSuccessful()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Registration(RegistrationModel rm)
        {
            User newU = new User();

            newU.Username = rm.Username;
            newU.Email = rm.Email;

            if (new UsersServ.WCFUsersClient().DoesUsernameExist(rm.Username) == false && new UsersServ.WCFUsersClient().DoesEmailExist(rm.Email) == false)
            {
                newU.Firstname = rm.FirstName;
                newU.Lastname = rm.LastName;
                newU.Address = rm.Address;
                newU.Town = rm.Town;

                if(rm.MobileNumber.Contains('+'))
                {
                    newU.MobileNumber = rm.MobileNumber;
                }
                else
                {
                    newU.MobileNumber = "+" + rm.MobileNumber;
                }
                
                newU.Password = rm.Password;
                newU.Country_FK = rm.CountryID;
                                                                               
                new UsersServ.WCFUsersClient().Register(newU);
                try
                {
                    //new UsersServ.WCFUsersClient().AllocateRole(newU, new UsersServ.WCFUsersClient().GetRole(1));
                }
                catch(Exception e)
                {
                    
                }
                
                return RedirectToAction("RegistrationSuccessful");
            }
            else
            {
                if (new UsersServ.WCFUsersClient().DoesUsernameExist(rm.Username) && new UsersServ.WCFUsersClient().DoesEmailExist(rm.Email) == true)
                {
                    ModelState.AddModelError("", "The username and Email address are already in use");
                }
                if (new UsersServ.WCFUsersClient().DoesUsernameExist(rm.Username) == true)
                {
                    ModelState.AddModelError("", "The username has already been taken. Please try a different username");
                }
                if (new UsersServ.WCFUsersClient().DoesEmailExist(rm.Email) == true)
                {
                    ModelState.AddModelError("", "The email address has already been taken. Please try a different e-mail");
                }
            }
            
            ModelState.AddModelError("", "One or errors were found. Please try again");
            return View(rm);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
